package com.example.demo02.server;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo02.dto.MessageInfo;
import lombok.Data;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/ws")
@Component
@Data
public class WebSocketServer {

    private static int onlineCount = 0;
    //客户端连接
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    //在线连接用户信息
    private static ConcurrentHashMap<String,Session> sessionPool=new ConcurrentHashMap<>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    private String username;

    @OnOpen
    public void onOpen(Session session) throws IOException {
        this.session=session;
        Map<String, List<String>> requestParameterMap = session.getRequestParameterMap();
        String username = requestParameterMap.get("username").get(0);
        this.username=username;
        webSocketSet.add(this);
        sessionPool.put(username,session);
        for (WebSocketServer webSocketServer : webSocketSet) {
            webSocketServer.session.getBasicRemote().sendText(username+"这小子上线了");
        }
    }
    @OnMessage
    public void onMessage(String message,Session session) throws IOException{
        MessageInfo messageInfo = JSON.parseObject(message, MessageInfo.class);
        sessionPool.get(messageInfo.getAcceptUser()).getBasicRemote().sendText(
                StrUtil.format("{}给你发了一条消息,内容是:{}",messageInfo.getSendUser(),messageInfo.getContent())
        );
        sessionPool.get(messageInfo.getSendUser()).getBasicRemote().sendText("消息发送出去了");
    }
    @OnClose
    public void onClose(Session session) throws IOException{
        Map<String, List<String>> requestParameterMap = session.getRequestParameterMap();
        String username = requestParameterMap.get("username").get(0);
        webSocketSet.remove(this);
        sessionPool.remove(username);
        for (WebSocketServer webSocketServer : webSocketSet) {
            webSocketServer.session.getBasicRemote().sendText(username+"这小子下线了");
        }
    }
    public static void sendMessage(String msg) throws IOException {
        for (WebSocketServer webSocketServer : webSocketSet) {
            webSocketServer.session.getBasicRemote().sendText(msg);
        }
    }

}

